# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(magrittr)
library(ropls)
library(optparse)
library(tidyverse)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

parent <- paste0("./")
createWhenNoExist(parent)
perFileName <- paste0(parent, "/OPLSDA_Permutation.csv")
pdfFileName <- paste0(parent, "/OPLSDA_Permutation.pdf")

plotData <- read.csv(perFileName, header = T)
nrow(plotData)

fixData <- plotData %>%
  filter(Similarity == 1) %>%
  head(1)

parameterData <- read_csv(str_c(parent, "/fitted_curve_parameter.csv"))
q2Row <- parameterData %>%
  filter(X1 == "Q2")
q2A <- q2Row[1, "slope"] %>%
  as.numeric()
q2B <- q2Row[1, "vertical intercept"] %>%
  as.numeric()

r2Row <- parameterData %>%
  filter(X1 == "R2")
r2A <- r2Row[1, "slope"] %>%
  as.numeric()
r2B <- r2Row[1, "vertical intercept"] %>%
  as.numeric()

lineX <- plotData$Similarity
lineY <- q2A * lineX + q2B
plotData$y <- lineY

lineY <- r2A * lineX + r2B
plotData$y1 <- lineY

plotData1 <- plotData %>%
  select(c("X", "Similarity", "Q2")) %>%
  rename(value = Q2) %>%
  mutate(class = "Q2", fill = q2yColor, pch = 22)

plotData2 <- plotData %>%
  select(c("X", "Similarity", "R2Y")) %>%
  rename(value = R2Y) %>%
  mutate(class = "R2", fill = r2yColor, pch = 21)
plotDf <- rbind(plotData1, plotData2) %>%
  mutate(pch = as.numeric(pch)) %>%
  mutate(class = factor(class, levels = c("R2", "Q2"))) %>%
  as.data.frame()

head(plotDf)
str(plotDf)

colDf <- plotDf %>%
  select(c("class", "fill")) %>%
  deframe()
pchDf <- plotDf %>%
  select(c("class", "pch")) %>%
  deframe()

labels <- c(substitute(paste(R^2, "Y=", R2Y), list(R2Y = fixData$R2Y)),
            substitute(paste(Q^2, "Y=", Q2), list(Q2 = fixData$Q2)))

p <- ggplot(plotDf, mapping = aes(x = Similarity, y = value)) +
  xlab("Correlation Coefficient") +
  ylab("") +
  ylim(c(-1, 1)) +
  xlim(c(0, 1.1)) +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 9, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'right',
        axis.title.y = element_text(size = 12), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 9, margin = margin(l = 0, unit = "cm"), hjust = 0), axis.title.x = element_text(size = 12), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), legend.spacing.x = unit(0, 'cm')
  ) +
  #0 line
  geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  #point
  geom_line(data = plotData, aes(x = Similarity, y = y, group = 1), linetype = 2, size = 1.2) +
  geom_line(data = plotData, aes(x = Similarity, y = y1, group = 1), linetype = 2, size = 1.2) +
  geom_point(aes(fill = class, pch = class), size = 3, color = "#000000") +
  scale_fill_manual("", values = colDf, labels = labels) +
  scale_shape_manual("", values = pchDf, labels = labels)

p <- getBasicPlotArg(p)

if (!is.na(legendTitle)) {
  p <- p +
    guides(fill = guide_legend(title = legendTitle), shape = guide_legend(title = legendTitle))
}


ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = height)




